/*
	商品添加
	功能：
		商品添加
*/

//登录信息
var adminLoginedInfo = Cookies.getJSON('kplus_ad_logined_info');
var p_type = getParam('pType')
var p_stock_by_size_region_tw = [], p_stock_by_size_region_cn = [];
//console.log(p_type)
//dom 加载完成
$(function(){
	layui.config({
	    base: './lib/layui/lay/modules/'  
	}).extend({
	    formSelects: 'formSelects'
	});
	layui.use(['layer', 'form', 'formSelects'], function(){
		var layer = layui.layer,
			form = layui.form,
			formSelects = layui.formSelects;

		//ajaxData
		var ajaxData = {
			aId: adminLoginedInfo.aId,
			aToken: adminLoginedInfo.aToken
		};
		//构建检索项		
		for (var i = 0; i < product_series_dict.length; i++){
			if (product_series_dict[i].type == p_type){
				$('select[name="series"]').append('<option value="'+ product_series_dict[i].series +'">'+ product_series_dict[i].name +'</option>')
			}
		}
		
		form.render();
		//活动 -- 存储
		var ptl_arr = [];
		//获取活动详情
		function getAccessPromotional(ajaxData) {
            $.ajax({
                url: BASE_SERVICEURL + URlS.ptl,
                type: 'GET',
                data: ajaxData,
                success: function (responseData) {
                    if (responseData.msg.code == 200) {
                        var ptlData = responseData.data;
                        var ptlBox = $('#ptlBox');
                        for (var i = 0; i < ptlData.length; i++) {
                            var ipt = DOMHTMLSTRINGS.active_select_btn(ptlData, i);
                            ptlBox.append(ipt);
                            //ptl_arr.push(ptlData[i].wPtl);
                        }
                        form.render('checkbox');
                    }else {
                        layer.close(loadIndex);
						layer.msg(MESSAGES.service_error, {time:2000, end: function(){
							//跳转500
							parent.layer.close(layer.index);
							window.parent.location.href = './500.html';
						}})
                    }
                },
                error: function (responseData) {
                    layer.msg(MESSAGES.service_error , { time: 2000, end: function(){
                    	location.href = './500.html';
                    }});
                }
            })
        };
        getAccessPromotional(ajaxData);

        //活动变更 checkbox 复选框监听
		form.on('checkbox(ptl)', function(data){
			if(data.elem.checked){   //选中
				ptl_arr.push(data.value);
			}else{   //取消
				var index = ptl_arr.indexOf(data.value);
				ptl_arr.splice(index, index + 1);
			}
		})

		//提交新增
		form.on('submit(newAdd)', function(data){
			formSelects.value('size', 'val').map(function(size){
				var key_tw = 'size_tw_' + size;
				var key_cn = 'size_cn_' + size;
				p_stock_by_size_region_tw.push({
					"size": size,
					"stock": data.field[key_tw]
				})
				p_stock_by_size_region_cn.push({
					"size": size,
					"stock": data.field[key_cn]
				})
			})
			layer.confirm(MESSAGES.confirm_add_product, {title:'提示'}, function(index){
				//console.log(data.field);
				//return false;
				newAddProduct(data.field);
				layer.close(index); //关闭询问框
			});
			function newAddProduct(field){
				var loadIndex = layer.load(1, { shade: [0.5, '#000'] });
				var data = field;
				var img_ipts = $('#product-imgs-form input.layui-input');
				var p_img = '';
				var pData = {
					pBrand: data.brand,
					pSeries:data.series,
                    pPrice: langTransObj(data.productPriceCn, data.productPriceTw, data.productPriceEn),
                    pName: langTransObj(data.productNameCn, data.productNameTw, data.productNameEn),
                    pStock: JSON.stringify({
                    	tw: p_stock_by_size_region_tw,
                    	cn: p_stock_by_size_region_cn
                    }),
                    pColor: data.productColor,
                    title: langTransObj(data.productTitleCn, data.productTitleTw, data.productTitleEn),
                    subTitle: langTransObj(data.productSubTitleCn, data.productSubTitleTw, data.productSubTitleEn),
                    intro: langTransObj(data.descCn, data.descTw, data.descEn),
                    pSize: formSelects.value('size', 'val').join("|"),
                    colorIcon:data.colorIconFileSrc,
                    accessPromotional: ptl_arr.join("|"),
                    sort: data.sortWeight,
                    freight: data.freightOverlay || 'N',
                    pType: p_type,
                    commend: data.is_commend 
				};
				img_ipts.each(function(index ,item){
					index == img_ipts.length - 1 ? p_img = p_img + $(item).val() : p_img = p_img + $(item).val() + '|';
				})
				pData['pImg'] = p_img;
				var _ajaxData = $.extend({}, pData, ajaxData);
				$.ajax({
					url: BASE_SERVICEURL + URlS.admin_product_api,
					type:'PUT',
					data: _ajaxData, 
					success: function(responseData){
						if(responseData.msg.code == 200){
							layer.close(loadIndex);
							layer.msg(MESSAGES.add_new_product_success, {time: 2000, end: function(){
								//关闭当前窗口并刷新父窗口
								parent.layer.close(layer.index);
                            	window.parent.location.reload();
							}})
						}else{
							layer.close(loadIndex);
							layer.msg(responseData.msg.msg, {time: 2000});
						}
					},
					error: function(responseData){
						layer.close(loadIndex);
						layer.msg(MESSAGES.service_error, {time:2000, end: function(){
							//跳转500
							parent.layer.close(layer.index);
							window.parent.location.href = './500.html';
						}})
					}
				})

			}
			return false;
		})	

		// 创建型号对应库存
		form.on('submit(create_stock_of_psize)', function(data){
			var size_values = formSelects.value('size', 'val');
			function create_temp (size, region){
				return '<div class="layui-input-inline">'+
				'<input type="text" name="size_'+region+'_'+size+'" autocomplete="off" required class="layui-input" placeholder="請輸入型號'+size+'的庫存"></div>';
			}
			var str_of_sizes_tw_html = '';
			var str_of_sizes_cn_html = '';
			size_values.map(function(val){
				str_of_sizes_tw_html += create_temp(val, 'tw');
				str_of_sizes_cn_html += create_temp(val, 'cn');
			})
			//添加 
			$('#TW_stock').append(str_of_sizes_tw_html);
			$('#CN_stock').append(str_of_sizes_cn_html);
			form.render();
			return false;
		})



	});
})









